求一段代码 sting[]转成bitarray

来源:百度知道 编辑:UC知道 时间:2024/07/03 04:41:38
Random rd=new Random();
int keyOrder=rd.Next(0,6);
string[] sn ={ "0000000100001000010000100", "0000000100011100000000000", "0000001100001000010000100", "0000000110001000010000100", "0000000100001000100001000", "0000000100001000001000010" };
byte[] a = Encoding.Default.GetBytes(sn[keyOrder]);
BitArray ba = new BitArray(a);
int struNum = 0;
foreach (bool b in ba)
{
if (b)
{
struNum++;
}
}

这个结果出来的struNum>50了,明显不对,怎么改?

你对BitArray的构建函数理解不清楚。
如果你想把string的二进制位1的表示为最后的bitarray的改为为一的话,想你那样不行, Encoding.Default.GetBytes 会把每个0和1 字符扩展成 8位,
其实你可以见到的把二进制值直接写到一个int数组里面用来初始化。
如果你还是想像你以前那样写,下面这个应该是你想要的吧

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace bitarrayLearn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Random rd = new Random();
int keyOrder = rd.Next(0, 6);
string[] sn = { "0000000100001000010000100", "0000000100011100000000000", "0000001100001000010000100", "0000000110001000010000100", "0000000100001000100001000", "000000010000100